<?php

namespace app\home\controller\service;

use app\common\model\OrderModel;
use app\common\model\PayRecharge;
use app\common\model\UserModel;
use app\common\model\VideoBuyUserVideo;
use app\common\model\VideoToVip;
use app\common\model\VideoType;
use app\common\model\VideoVipLevel;
use app\common\model\OrderVideo;
use app\common\model\Video;
use app\common\traites\GetTreeTrait;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use \think\facade\Request;

class GoodsService
{
    use GetTreeTrait;

    public $model;

    public function video_model()
    {
        $this->model = new VideoType();
        return $this;
    }

    public function level_model()
    {
        $this->model = new VideoVipLevel();
        return $this;
    }

    //查询所有套餐
    public function video_level(int $type = 1)
    {
        $list = (new VideoVipLevel())->where(['status'=>1,'type'=>$type])->select();
        return $list;
    }

    //获取已经购买的单独视频列表
    public function alone_list()
    {
        //当前页
        $page = Request::post('page/d', 1);
        //每页显示数量
        $limit = Request::post('limit/d', 10);

        $type = Request::post('type/d', 0);
        //查询条件
        $map=[];
        if ($type > 0) $map['type'] = $type;

        $home_user = session('home_user');


        return (new VideoBuyUserVideo())->user_list($home_user['id'],$limit,$page,$map);
    }

    //查询用户已经购买的额视频套餐
    public function user_video_level()
    {
        $home_user = session('home_user');
        //查询用户购买的套餐
        $order_video = (new OrderVideo())->user_level($home_user['id']);
        if (empty($order_video)) return false;
        return $order_video->toArray();
        //$order_video=$order_video->toArray();
    }

    //获取视频列表
    public function user_video_list($user_video_level = 0)
    {
        //当前页
        $page = Request::post('page/d', 1);
        //每页显示数量
        $limit = Request::post('limit/d', 10);
        //视频分类
        $type = Request::post('type/d', 0);
        //查询条件
        $map['status'] = 1;
        if ($type > 0) $map['type'] = $type;

        $list = (new VideoToVip())->alias('a')
            ->field('b.*')
            ->where($map)
            ->join('video b', 'a.video_id=b.id','right');

        if (!empty($user_video_level) || $user_video_level!=0) {
            $list = $list->whereLike('types', '%' . $user_video_level['vip_level'] . '%')->whereOr('types',null);
        }

        $list = $list->order('b.update_time desc,b.id desc')
            ->paginate(['list_rows' => $limit, 'page' => $page]);
        if (empty($list)) return false;
        return $list;
    }

    //视频详情
    public function user_video_details()
    {
        $id = Request::post('id/d', 0);
        //视频ID错误
        if ($id <= 0) return false;
        //查询视频
        $find = (new Video())->find($id);
        //没有该视频
        if (empty($find)) return false;
        //is_purchase 1可观看  2需要单独购买 5不可观看
        $find->is_purchase=5;
        #开始  查看当前用户是否具备查看该视频的资格
        $find = $this->alone_purchase($find);
        #结束
        return $find;
    }

    //查询视频分类
    public function video_type_list()
    {
        $find = $this->model->field('id,pid,title')
            ->where('is_show', 1)
            ->order('sort desc,id desc')
            ->select();
        if (empty($find)) return false;
        $find = $find->toArray();
        array_unshift($find, ['id' => 0, 'pid' => 0, 'title' => '全部']);
        return $this->fillModelBackends($find);
    }
    /**
     * 充值
     * @param int $rechargeId
     * @param int $price
     * @return array
     */
    public function recharge_price(int $rechargeId,int $price)
    {
        //事务操作。  充值成功   充值订单，支付成功写入充值列表，并写入用户金额,写入用户累计充值
        //充值订单，支付成功写入充值列表
        $data['sys_bank_id'] = '收款账号';
        $data['u_bank_name'] = '打款银行名';
        $data['u_bank_user_name'] = '打款用户名';
        $data['u_bank_card'] = '打款银行卡号';
        $data['success_time'] = date('Y-m-d H:i:s');


        $update =false;
        Db::startTrans();
        try {
            //写入充值订单  //写入用户累计充值
            (new PayRecharge())->where('id',$rechargeId)->save($data);
            //用户金额修改
            (new UserModel())->where('id',session('home_user.id'))
                ->save(['money_balance' => session('home_user.money_balance') + $price]);
            $update=true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($update) return ['code' => 1, 'msg' => '支付成功','order_id'=>$rechargeId];

        $msg = '支付成功。写入充值订单信息失败，请联系管理员';
        Log::critical('订单ID：'.$rechargeId.':'.$msg);
        return ['code' => 1, 'msg' => $msg,'order_id'=>$rechargeId];
    }
    //充值金额
//    public function recharge_price($request)
//    {
//        //获取充值金额
//        $price = $request->post('price/d', 0);
//        if ($price <= 0) ['code' => 0, 'msg' => '充值金额错误'];
////        if ($price <= 0) return false;
//
//        $admin = session('home_user');
//        //生成充值订单
//        $save = $this->recharge_user($admin, $price);
//
//        //发起付款
//        if (!$save)  ['code' => 0, 'msg' => '支付失败'];
//        //if (!$save)  return false;
//        //事务操作。  充值成功   充值订单，支付成功写入充值列表，并写入用户金额,写入用户累计充值
//        //充值订单，支付成功写入充值列表
//        $data['sys_bank_id'] = '收款账号';
//        $data['u_bank_name'] = '打款银行名';
//        $data['u_bank_user_name'] = '打款用户名';
//        $data['u_bank_card'] = '打款银行卡号';
//        $data['success_time'] = date('Y-m-d H:i:s');
//
//        //写入用户累计充值
//        $model = (new PayRecharge());
//        //充值订单
//
//        $update = $model->where('id',$save)->save($data);
//        if ($update) return ['code' => 1, 'msg' => '支付成功','order_id'=>$save];
//        //if ($update) return intval($save);
//        $msg = '支付成功。写入充值订单信息失败，请联系管理员';
//        Log::critical('订单ID：'.$save.':'.$msg);
//        return ['code' => 1, 'msg' => $msg,'order_id'=>$save];
//    }

    //充值订单写入
    public function recharge_user($admin, $price)
    {
        event('RepeatPurchase',['repeat'=>true,'id'=>$admin['id']]);
        $model = (new PayRecharge());
        $order = [
            'create_time' => date('Y-m-d H:i:s'),
            'money' => $price,
            //'admin_uid' => $admin['admin_uid'],
            'uid' => $admin['id'],
            'u_ip' => $_SERVER['REMOTE_ADDR'],
            'market_uid' => $admin['market_uid'],
            'u_city' => '',
            'sys_bank_id' => '',
            'u_bank_name' => '',
            'u_bank_user_name' => '',
            'u_bank_card' => '',
        ];

        $save = $model->save($order);
        if ($save) return ['code'=>1,'购买成功','recharge_id'=>$model->id];;
        return ['code'=>0,'msg'=>'订单生成失败'];
    }

    //购买套餐
    public function purchase_video_level()
    {
        event('RepeatPurchase',['repeat'=>true,'id'=>session('home_user.id')]);
        $id = Request::post('id/d', 0);
        if ($id <= 0) return ['code' => 0, 'msg' => '商品ID错误'];
        //查询当前商品价格。并生成订单号。发送支付 到订单平台
        $find = (new VideoVipLevel())->find($id);
        if (!$find) return ['code' => 0, 'msg' => '商品不存在'];
        $find = $find->toArray();
        //生成订单号。
        $code = orderCode();
        //购买成功后直接写入订单

        //添加订单
        $save = $this->order_user($id, $find, $code);
        if (!$save->id) return ['code' => 0, 'msg' => '订单写入失败'];//订单写入失败
        //查看余额是否够
        $admin = session('home_user');

        //余额够直接扣除
        $money_balance = $admin['money_balance'] - $find['price_vip'];
        if ($money_balance >= 0) {
            $is_true = $this->user_price($admin, $find['price_vip'], $save->id);
            if (!$is_true) return ['code' => 0, 'msg' => '余额扣除失败'];//购买失败
        } else {
            //不够在发送到支付平台
            //发送支付 到订单平台
            $order_code = [
                'name' => $find['title'],
                'price' => $find['price_vip'],//价格
                'order' => $code,
            ];
            //发送失败
            //if (false){}
        }

        //支付成功。修改订单状态.并写入到期时间到 video 订单表
        //修改订单状态
        $status = $save->where('id', $save->id)->save(['pay_status' => 1, 'pay_time' => date('Y-m-d H:i:s')]);

        if (!$status) {
            Log::emergency('订单号:'.$code . '：' . '购买成功，订单状态修改失败,联系管理员');
        }
        //增加到 视频订单表
        $vip = $this->order_vip($save->id, $find);
        if (!$vip) {
            Log::emergency('订单号:'.$code . '：' . '购买成功，视频订单表写入失败,联系管理员');
        }

        //分销奖励分配 小于0 表示是走支付平台来的购买套餐金额
        if ($money_balance < 0) {
            //现在是不管是充值还是购买都能得到分销奖励
            $BranchService = new BranchService();
            $money_log = $BranchService->branch($admin, ['price' => $find['price_vip'], 'order_id' => $save->id]);
            //if ($money_log['code'] == 0) return $money_log;
        }
        return ['code' => 1, 'msg' => '购买成功'];
    }
    //视频单独购买
    public function alone_video_purchase()
    {
        $id = Request::post('id/d',0);
        if ($id == 0) return ['code'=>0,'ID错误'];
        //查询当前商品价格。并生成订单号。发送支付 到订单平台
        $find = (new Video())->find($id);
        if (!$find) return ['code' => 0, 'msg' => '商品不存在'];
        if ($find->video_price <= 0 ) return ['code' => 0, 'msg' => '商品价格不存在'];
        //生成订单号
        $code = orderCode();
        //添加订单
        $save = $this->order_user($id, $find, $code);
        if (!$save->id) return ['code' => 0, 'msg' => '订单写入失败'];//订单写入失败
        //查看余额是否够
        $admin = session('home_user');

        //余额够直接扣除
        $money_balance = $admin['money_balance'] - $find['video_price'];
        if ($money_balance >= 0) {
            $is_true = $this->user_price($admin, $find['video_price'], $save->id);
            if (!$is_true) return ['code' => 0, 'msg' => '余额扣除失败'];//购买失败
        } else {
            //不够在发送到支付平台
            //发送支付 到订单平台
            $order_code = [
                'name' => $find['title'],
                'price' => $find['video_price'],//价格
                'order' => $code,
            ];
            //发送失败
            //if (false){}
        }
        //支付成功。修改订单状态.并写入到期时间到 video 订单表
        //修改订单状态
        $status = $save->where('id', $save->id)->save(['pay_status' => 1, 'pay_time' => date('Y-m-d H:i:s')]);
        if (!$status) {
            Log::emergency('订单号:'.$code . '：' . '购买成功，订单状态修改失败,联系管理员');
        }

        //增加到用户单独购买视频表
        $vip = (new VideoBuyUserVideo())->insert([
            'video_id'=>$id,
            'uid'=>$admin['id'],
            'start_time'=>date('Y-m-d H:i:s'),
            'end_time'=>date('Y-m-d H:i:s',strtotime("+1 day")),
        ]);
        if (!$vip) {
            Log::emergency('订单号:'.$code . '：' . '购买成功，视频订单表写入失败,联系管理员');
        }

        //分销奖励分配 $money_balance小于0 表示是走支付平台来的购买套餐金额
        if ($money_balance < 0) {
            $BranchService = new BranchService();
            $money_log = $BranchService->branch($admin, ['price' => $find['video_price'], 'order_id' => $save->id]);
            if ($money_log['code'] == 0) return $money_log;
        }

        return ['code' => 1, 'msg' => '购买成功'];

    }
    public function user_price($admin, $price, $order)
    {
        $save = false;
        //写入消费日志
        Db::startTrans();
        try {
            (new UserModel())->where('id', $admin['id'])->save(['money_balance' => $admin['money_balance'] - $price]);
            //写操作日志
            (new \app\common\model\MoneyLog())->insert([
                'create_time' => date('Y-m-d H:i:s'),
                'type' => 3,
                'status' => 101,
                'money_before' => $admin['money_balance'],
                'money_end' => $admin['money_balance'] - $price,
                'money' => $price,
                'uid' => $admin['id'],
                'market_uid' => $admin['market_uid'],
                'source_id' => $order,
                'mark' => '购买会员'
            ]);
            $save = true;
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            // 验证失败 输出错误信息
            return $e->getError();

        }

        return $save;
    }

    //写入订单
    private function order_user($id, $find, $code)
    {
        //组装订单数据
        $order_user = [
            'uid' => session('home_user.id'),
            'market_uid' => session('home_user.market_uid'),
            'admin_uid' => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'status' => 0,
            'goods_id' => $id,
            //'pay_time' => date('Y-m-d H:i:s'),
            'pay_status' => 0,
            'pay_price' => isset($find['price_vip']) ? $find['price_vip']:$find['video_price'],
            'pay_no' => $code,
            'describe_order' => '购买商品' . $find['title'],
            'goods_info' => json($find),
            'pay_channel' => '前台购买',
            'ip' => $_SERVER['REMOTE_ADDR']
        ];
        $model = new OrderModel();
        $save = $model->save($order_user);
        if ($save) return $model;
        return false;
    }

    //订单成功 写入视频vip表
    private function order_vip($order_id, $find)
    {
        //写入vip订单信息
        $status = (new OrderVideo())->save([
            'uid' => session('home_user.id'),
            'market_uid' => session('home_user.market_uid'),
            'status' => 1,
            'order_id' => $order_id,
            'vip_level' => $find['id'],
            'vip_start_time' => date('Y-m-d H:i:s'),
            'vip_end_time' => date('Y-m-d H:i:s', time() + ($find['validity_time'] * 60)),//当前时间+可观看秒
        ]);
        if ($status) return true;
        return false;
    }

    //查看是否购买当前视频的权限
    private function alone_purchase($find)
    {
        //查看是否开通了会员
        $home_user = session('home_user');
        //查询用户购买的套餐

        $order_video = (new OrderVideo())->user_level($home_user['id']);
        //购买了套餐，查看是否该套餐是否具备查看该视频资格
        // $find->video_price 说明不是单片购买的视频
        if (!empty($order_video)){
            $res = (new VideoToVip())->qualifications($order_video->vip_level,$find->id);
            if ($res) {
                $find->is_purchase=1;
                return $find;
            }//没有该套餐，并且该视频没有价格。表示可免费观看
            elseif ($find->video_price == 0){
                $find->is_purchase=1;
                return $find;
            }

        }

        //需要单独购买的视频
        if ($find->video_price >0 ) $find->is_purchase=2;

        //查看用户是否对当前视频单独购买了
        $alone_video = (new VideoBuyUserVideo())->alone_purchase($home_user['id'],$find->id);
        if ($alone_video) $find->is_purchase = 1;

        return $find;
    }

}